package com.zc.portal.infra.security.voter;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

public class UrlRoleBaseVoter implements AccessDecisionVoter<Object> {
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) {

        if (authentication == null) {
            return ACCESS_DENIED;
        }

        int voteResult = ACCESS_ABSTAIN;

        Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);

        for (ConfigAttribute configAttribute : configAttributes) {
            if (configAttribute == null) {
                continue;
            }
            //拥有其中一个角色即可通过
            if (this.supports(configAttribute)) {
                for (GrantedAuthority grantedAuthority : authorities) {
                    if (configAttribute.getAttribute().equals(grantedAuthority.getAuthority())) {
                        return ACCESS_GRANTED;
                    }
                }
            }
        }
        return voteResult;
    }

    private Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
        return authentication.getAuthorities();
    }
}
